package com.mapaower.payment.controller;

import com.mapaower.payment.entity.MembershipRecharge;
import com.mapaower.payment.entity.MembershipType;
import com.mapaower.payment.service.MembershipService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/membership")
@RequiredArgsConstructor
public class MembershipController {

    private final MembershipService membershipService;

    /**
     * 获取所有启用的会员类型
     */
    @GetMapping("/types")
    public ResponseEntity<List<MembershipType>> getEnabledMembershipTypes() {
        return ResponseEntity.ok(membershipService.getEnabledMembershipTypes());
    }

    /**
     * 创建会员充值订单
     */
    @PostMapping("/recharge")
    public ResponseEntity<MembershipRecharge> createRechargeOrder(
            @RequestParam Long userId,
            @RequestParam Long membershipTypeId,
            @RequestParam MembershipRecharge.PaymentMethod paymentMethod) {
        return ResponseEntity.ok(membershipService.createRechargeOrder(userId, membershipTypeId, paymentMethod));
    }

    /**
     * 更新会员类型启用状态 (管理员接口)
     */
    @PutMapping("/types/{typeId}/status")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<MembershipType> updateMembershipTypeStatus(
            @PathVariable Long typeId,
            @RequestParam boolean enabled) {
        return ResponseEntity.ok(membershipService.updateMembershipTypeStatus(typeId, enabled));
    }

    /**
     * 查询用户充值记录
     */
    @GetMapping("/recharges")
    public ResponseEntity<List<MembershipRecharge>> getUserRechargeRecords(
            @RequestParam Long userId,
            @RequestParam(required = false) MembershipRecharge.RechargeStatus status) {
        return ResponseEntity.ok(membershipService.getUserRechargeRecords(userId, status));
    }

    /**
     * 支付回调接口
     */
    @PostMapping("/payment/callback/{paymentMethod}")
    public ResponseEntity<String> handlePaymentCallback(
            @PathVariable String paymentMethod,
            @RequestParam Map<String, String> callbackParams) {
        return ResponseEntity.ok(membershipService.handlePaymentCallback(paymentMethod, callbackParams));
    }
}